
from django.views.generic import TemplateView
from elasticsearch import Elasticsearch
from django.http import JsonResponse


class SearchAnswerview(TemplateView):

    def get(self, request):
        es = Elasticsearch(['192.168.1.140'], http_auth=('elastic', 'changeme'), port=9200, timeout=10)
        query = request.GET['q']
        query_json = {
            'query': {
                "bool": {
                    "must": {
                        "match": {
                            "Title": query
                        }
                    },
                    # "filter": {
                    #     "range": {
                    #         "age": {"gt": 30}
                    #     }
                    # }
                }
            }
        }
        res = es.search(index="stackoverflow",
                        doc_type='java', body=query_json)
        top_10_recodes = res['hits']['hits']
        i = 0
        for recode in top_10_recodes:
            ques_id = recode['_source']['Id']
            ans_body = self.get_ans_by_id(ques_id, es)
            recode['ans'] = ans_body
            top_10_recodes[i] = recode
            i = i + 1
        data = {
            'top_10_recodes': top_10_recodes,
        }
        return JsonResponse(data)

    def get_ans_by_id(self, question_id, es):

        query_json = {
            'query': {
                "bool": {
                    "must": {
                        "match": {
                            "ParentId": question_id
                        }
                    },
                    # "filter": {
                    #     "range": {
                    #         "age": {"gt": 30}
                    #     }
                    # }
                }
            }
        }
        res = es.search(index="answer", doc_type='java', body=query_json)
        res_ans = res['hits']['hits']
        ans_body = {}
        i = 0
        for recode in res_ans:
            ans_body[i] = recode['_source']['Body']
            i = i + 1
        return ans_body
